<template>
  <el-row class="login-row">
    <el-col :span="6" :offset="9">
      <el-card class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <div>科泰购后台登录</div>
        </div>
        <el-form :model="loginForm" status-icon :rules="rules" ref="loginForm"
                 label-width="80px" class="demo-loginForm">
          <el-form-item label="用户名" prop="username">
            <el-input type="text" v-model="loginForm.username" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="loginForm.password" show-password
                      autocomplete="off">
            </el-input>
          </el-form-item>
          <div class="login-btn">
            <el-button type="primary" @click="submitForm('loginForm')">登录</el-button>
          </div>
        </el-form>
      </el-card>
    </el-col>
  </el-row>
</template>

<script>
  // 引用qs插件用于处理表单数据
  import qs from 'qs'

  export default {
    data() {
      return {
        loginForm: {
          username: '',
          password: '',
        },
        rules: {
          username: [
            { required: true, message: '请输入用户名！', trigger: 'blur' },
            {
              min: 3,
              max: 10,
              message: '用户名长度在 3 到 10 个字符',
              trigger: 'blur',
            },
          ],
          password: [
            { required: true, message: '请输入密码！', trigger: 'blur' },
            // 正则校验
            { pattern: /^\w{6,}$/, message: '密码为6位以上数字字母下划线组合！', trigger: 'blur' },
          ],
        },
      }
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
             // this.$message.success('校验成功');
            let queryStr = qs.stringify(this.loginForm);
            // 发送登录请求
            this.$axios
              .post('/api/login', queryStr)
              .then((res) => {
                // code为0表示成功，否则为失败
                if (res.data.code === 0) {
                  // 登录的用户数据保存在data中
                  let userInfo = res.data.data;
                  // 登录成功
                  this.$message.success(`${userInfo.nickname}登录成功！`)
                  // 通过commit调用mutations中的login函数，将用户信息保存到Vuex
                  this.$store.commit('login', userInfo)
                  // 编程式路由跳转到/main
                  this.$router.push({ path: '/main' })
                } else {
                  // 显示错误信息
                  this.$message.error(res.data.msg)
                }
              })
          } else {
            this.$message.success('校验失败，请重新填写！');
            return false
          }
        })
      },
    },
  }
</script>

<style>
  .login-row {
    margin-top: 100px;
    min-width: 800px;
  }
  .login-row .login-btn {
    text-align: center;
  }
</style>
